package com.lin.service.qanda;

import com.lin.common.constant.CommonConstant;
import com.lin.common.error.CustomRuntimeException;
import com.lin.common.utils.BeanCopyUtils;
import com.lin.common.utils.CustomFileUtils;
import com.lin.common.utils.DateUtils;
import com.lin.common.utils.RedisSerializableUtils;
import com.lin.controller.req.AddQuestionsReqMsg;
import com.lin.controller.res.QuestionsPageResMsg;
import com.lin.dao.QuestionsMapper;
import com.lin.po.Questions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class QuestionsServiceImpl implements QuestionsService {
    @Autowired
    private QuestionsMapper questionsMapper;
    @Value("${cs.prefix-path}")
    private String prefixPath;

    @Value("${cs.visit.url}")
    private String visitUrl;

    @Override
    public QuestionsPageResMsg list(Long customerId, Integer pageSize, Integer pageNo) {
        QuestionsPageResMsg qp = new QuestionsPageResMsg();
        List<Questions> list = questionsMapper.list(customerId, pageSize, pageNo).stream().map(i -> {
            i.setFileurl(i.getFileurl().replace(prefixPath, visitUrl));
            return i;
        }).collect(Collectors.toList());
        qp.setRecords(list);
        qp.setTotal(questionsMapper.listcount(customerId));
        return qp;
    }

    @Override
    public Integer save(AddQuestionsReqMsg reqMsg) throws CustomRuntimeException, IOException {
        Questions q = BeanCopyUtils.beanCopy(reqMsg, Questions.class);
        if (null != reqMsg.getFileurl()) {
            //转换file 的base64为文件存储
            String url = CustomFileUtils.buildFile(reqMsg.getFileurl(), CommonConstant.DEFAULT_PREFIX, prefixPath, RedisSerializableUtils.generateOrderNo(CommonConstant.DEFAULT_LENGTH));
            q.setFileurl(url);
        }
        q.setUpdateTime(DateUtils.fullDateFormat());
        if (null == q.getId()) {
            q.setId(Long.parseLong(RedisSerializableUtils.generateForLong(CommonConstant.DEFAULT_LENGTH)));
            q.setCreateTime(DateUtils.fullDateFormat());
            return questionsMapper.insertSelective(q);
        } else {
            return questionsMapper.updateByPrimaryKeySelective(q);
        }
    }
}
